﻿using System;
using System.Collections.Generic;
using System.Text;

namespace testProtobuf.Network
{
    class StreamHelper
    {
        static bool CheckSteamOOB(int offset, int size, int length)
        {
            if (offset + size > length)
            {
                Console.WriteLine("Stream Out of Bounds");
                return false;
            }

            return true;
        }

        public static bool ReadHead(ref NetworkStream networkStream, ref NetworkHead head)
        {

            return true;
        }

        public static bool ReadInt(ref NetworkStream networkStream, ref int value)
        {
            int length = networkStream.getValidBufferLength();
            int streamOffset = networkStream.getOffset();
            if (!CheckSteamOOB(streamOffset, 4, length))
                return false;

            byte[] bytes = networkStream.getByteData();
            value = (int)bytes[streamOffset];
            value += (int)bytes[streamOffset + 1] << 8; 
            value += (int)bytes[streamOffset + 2] << 16;
            value += (int)bytes[streamOffset + 3] << 24;
            streamOffset += 4;
            return true;
        }

        public static bool ReadByteArray(ref NetworkStream networkStream, ref byte[] byteArray)
        {
            int size = 0;
            if (!ReadInt(ref networkStream, ref size))
                return false;

            int length = networkStream.getValidBufferLength();
            int streamOffset = networkStream.getOffset();

            if (!CheckSteamOOB(streamOffset, size, length))
            {
                byteArray = null;
                return false;
            }


             byte[] bytes = networkStream.getByteData();
             byteArray = new byte[size];

            for (int i = 0; i < size; i++)
            {
                byteArray[i] = bytes[streamOffset + i];
            }
            streamOffset += size;

            return true;
        }

        public static bool WriteInt(ref NetworkStream networkStream, int value)
        {
            int length = networkStream.getValidBufferLength();
            int totalLength = networkStream.getTotalBufferLength();

            if (!CheckSteamOOB(length, 4, totalLength))
                return false;

            byte[] bytes = new byte[4];
            bytes[0] = (byte)(value & 0x000000ff); 
            bytes[1] = (byte)((value & 0x0000ff00) >> 8);
            bytes[2] = (byte)((value & 0x00ff0000) >> 16);
            bytes[3] = (byte)((value & 0xff000000) >> 24);
            networkStream.Append(bytes, 4);
            return true;

        }

        public static void WriteByteArray(ref NetworkStream networkStream, byte[] byteArray)
        {
            
        }
    }
}
